package com.lanou.musicbox.fragment.onlinemusic;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.lanou.musicbox.R;
import com.lanou.musicbox.adapter.onlinemusic.PlaylistAdapter;
import com.lanou.musicbox.base.BaseFragment;
import com.lanou.musicbox.bean.SingerMenu;
import com.lanou.musicbox.utils.Contant;
import com.lanou.musicbox.utils.NetWorkUtils;
import com.lanou.musicbox.utils.SwipeRefreshLoadingLayout;
import com.lanou.musicbox.utils.VolleySingleton;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;


/**
 * Created by 赵宝龙 on 15/10/21.
 * 网络音乐_歌单页面
 */
public class PlaylistFragment extends BaseFragment implements
        AdapterView.OnItemClickListener, SwipeRefreshLoadingLayout.OnLoadListener,
        SwipeRefreshLoadingLayout.OnRefreshListener {
    private GridView playlistGridView;
    private PlaylistAdapter adapter;
    private VolleySingleton volleySingleton;
    private List<SingerMenu.ContentEntity> datas;
    private SwipeRefreshLoadingLayout refreshLoadingID;
    private FragmentManager manager;
    private String newUrl;
    private int page = 0;
    private boolean isConnect;
    private ProgressDialog dialog;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_songs, null);
        playlistGridView = (GridView) v.findViewById(R.id.playlistGridView);
        refreshLoadingID = (SwipeRefreshLoadingLayout) v.findViewById(R.id.refreshLoadingID);
        refreshLoadingID.setOnLoadListener(this);
        refreshLoadingID.setOnRefreshListener(this);
        playlistGridView.setOnItemClickListener(this);
        volleySingleton = VolleySingleton.getVolleySingleton(getActivity());
        isConnect = NetWorkUtils.checkNet(getActivity());
        dialog=new ProgressDialog(getActivity());

        initData();// 定义一个方法用来解析

        return v;
    }

    private void initData() {
        datas = new ArrayList<>();
        page = 1;
        String url = Contant.Url.URL_PlayList+page;
        StringRequest request = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                SingerMenu s = gson.fromJson(response, SingerMenu.class);
               // Log.e("ZBL", "===================" + response);
                datas = s.getContent();
               // Log.e("ZBL", "===================" + datas.get(0).getCollectnum());
                adapter = new PlaylistAdapter(getActivity(), datas);
                playlistGridView.setAdapter(adapter);
                comicinterface(i);
                if (dialog.isShowing()){
                    dialog.dismiss();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (isConnect){
                    Toast.makeText(getActivity(), R.string.no_network, Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(getActivity(), R.string.connect_error, Toast.LENGTH_SHORT).show();
                }
            }
        });
        volleySingleton.addQueue(request);
        if (isConnect){
            dialog.setMessage("数据加载中.....");
            dialog.show();
        }
    }

    private void comicinterface(int page){
        newUrl = Contant.Url.URL_PlayList+page;
        Log.e("CXXXXXX",newUrl);
        StringRequest comicRequest = new StringRequest(newUrl, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.i("PlaylistFragment","->加载成功");
                Gson gson = new Gson();
                SingerMenu s = gson.fromJson(response, SingerMenu.class);
                datas = s.getContent();
                if (flag) {
                    PlaylistFragment.this.datas.clear();
                }

                adapter.addData(datas);

                // 定义方法
                finishRefreshOrLoading();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // 解析失败调用此方法
                finishRefreshOrLoading();
                Log.i("PlaylistFragment","->加载失败");
            }
        });
        volleySingleton.addQueue(comicRequest);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
       // mainFragmentActivity = (MainFragmentActivity) getActivity();
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        //mainFragmentActivity.jump(adapter.getUrl(i));
        manager = getActivity().getSupportFragmentManager();
        EnterThePlaylistFragment fragment = new EnterThePlaylistFragment();
        Bundle bundle = new Bundle();
        bundle.putString("songs_id", adapter.getUrl(i));
        fragment.setArguments(bundle);
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.addToBackStack(null);
        transaction.replace(R.id.fill_main, fragment);
        transaction.commit();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void finishRefreshOrLoading() {
        refreshLoadingID.setRefreshing(false);
        refreshLoadingID.setLoading(false);
    }

    private int i = 1;
    private boolean flag = true;

    @Override
    public void onLoad() {
        flag = false;
        comicinterface(++i);
        Log.e("ZBL", "--------------------加载了>");
    }

    @Override
    public void onRefresh() {
        i = 1;
        flag = true;
        comicinterface(i);
    }

}

